package com.mattgarner.jaddas.node.command.dml;

import com.mattgarner.jaddas.common.ResultSet;
import com.mattgarner.jaddas.common.ResultSetHeader;
import com.mattgarner.jaddas.dataset.DataSet;
import com.mattgarner.jaddas.node.DataSetManager;
import com.mattgarner.jaddas.node.RemoteClient;
import com.mattgarner.jaddas.node.command.CommandParser;
import com.mattgarner.jaddas.node.data.LocalTableDataProvider;
import com.mattgarner.jaddas.node.net.Protocol;
import com.mattgarner.jaddas.node.net.Worker;

public class CmdSelect extends CommandParser {

	public CmdSelect(Worker serverWorker, RemoteClient client) {
		super(serverWorker, client);
	}
	
	// SELECT FROM DATASET
	public final boolean parseCommand(String command) {
		Worker worker = getServerWorker();
		RemoteClient clientConfig = getRemoteClient();
	
		String[] cmd = extractRegexGroups("(?i)^SELECT\\s+(.*?)\\s+FROM\\s+([A-Z0-9_\\.]+)\\s*(.*?)$", command);
		String dsColumnNames = cmd[0];
		String dsName = cmd[1];
		
		DataSetManager dsManager = DataSetManager.getInstance();
		DataSet dataSet = dsManager.getDataSetByName(dsName);
		
		if(dataSet == null) {
			worker.sendMessage(Protocol.MSG_NAK, "DataSet '"+dsName+"' does not exist.");
			return true;
		}
		
		try { 
			ResultSetHeader rsHeader = dataSet.getDataTableHeader().convertToResultSetHeader(clientConfig.getStringEncoding());
			LocalTableDataProvider dsDataProvider = new LocalTableDataProvider(dataSet);
			ResultSet resultSet = dsDataProvider.getFullTableDataResultSet(clientConfig.getStringEncoding());
			sendResultSet(resultSet);
			return true;
		} catch(Exception e) {
			worker.sendMessage(Protocol.MSG_NAK, "Exception: " + e.getMessage());
			return true;
		}
	}

}
